package com.xbsg.protocol.xf.server.netty;

import com.xbsg.protocol.xf.server.HexEcodeUtil;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
public class MyMessageDecoder extends ByteToMessageDecoder {

    private static Map<ChannelHandlerContext, String> msgBufMap = new ConcurrentHashMap<>();
    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        byte[] data = new byte[in.readableBytes()];
        in.readBytes(data);
        String msg = HexEcodeUtil.ByteArrayToHexStr(data);
        log.info("MyMessageDecoder解码器接收消息： " + msg);
        // 处理粘包拆包问题
        if (msg.startsWith("4040")) {
            if (msg.endsWith("2323")) {
                out.add(msg);
                //log.info("接收完整数据成功： " + msg);
            } else {
                msgBufMap.put(ctx, msg);
                log.info("接收完整数据失败："+ msg);
            }
            //todo 拆包有问题,可以校验和
        } else if (msg.endsWith("2323") && msgBufMap.containsKey(ctx)) {
           msg = addTwoArray(msgBufMap.get(ctx),msg.split("2323")[0]);
           out.add(msg);
           //log.info("解析拆包数据成功： " + msg);
           msgBufMap.remove(ctx);
        }
    }

/*    public byte[] addTwoArray(byte[] btX, byte[] btY){
        //定义目标数组  目标数组应该等于将要拼接的两个数组的总长度
        byte[] btZ = new byte[btX.length + btY.length];

        System.arraycopy(btX, 0, btZ, 0, btX.length);
        System.arraycopy(btY, 0, btZ, btX.length, btY.length);
        return btZ;
    }*/

    public String addTwoArray(String btX, String btY){
        //定义目标数组  目标数组应该等于将要拼接的两个数组的总长度
        String btZ = btX + btY;

        return btZ;
    }

}
